using MediatR;
using RBAC.Domain.ProcessManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ProcessManagements;
using Dapper;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace RBAC.Read.Api.Application.Handler.ProcessManagements
{
    /// <summary>
    /// 工序分类导出处理器（读端）
    /// </summary>
    public class ExportProcessClassificationsHandler : IRequestHandler<ExportProcessClassificationsCommand, APIResult<byte[]>>
    {
        private readonly IBaseRepository<ProcessClassification> _repo;

        public ExportProcessClassificationsHandler(IBaseRepository<ProcessClassification> repo)
        {
            _repo = repo;
        }

        public async Task<APIResult<byte[]>> Handle(ExportProcessClassificationsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var where = string.Empty;
                var param = new DynamicParameters();

                var conditions = new List<string>();
                if (!string.IsNullOrWhiteSpace(request.Keyword))
                {
                    conditions.Add("(ClassificationCode LIKE @kw OR ClassificationName LIKE @kw)");
                    param.Add("@kw", $"%{request.Keyword}%");
                }
                if (request.Status.HasValue)
                {
                    conditions.Add("Status = @Status");
                    param.Add("@Status", request.Status.Value);
                }
                if (conditions.Count > 0)
                {
                    where = string.Join(" AND ", conditions);
                }

                var data = _repo.GetAll(where, param)?.ToList() ?? new List<ProcessClassification>();
                if (data.Count == 0)
                {
                    return new APIResult<byte[]>
                    {
                        Code = APIEnums.Fail,
                        Msg = "没有可导出的工序分类数据",
                        Data = Array.Empty<byte>()
                    };
                }

                var wb = new XSSFWorkbook();
                var sheet = wb.CreateSheet("工序分类");

                var headers = new[] { "分类编号", "分类名称", "排序", "状态", "备注", "创建时间", "创建人" };
                var headerRow = sheet.CreateRow(0);
                for (int i = 0; i < headers.Length; i++)
                {
                    headerRow.CreateCell(i).SetCellValue(headers[i]);
                }

                for (int r = 0; r < data.Count; r++)
                {
                    var m = data[r];
                    var row = sheet.CreateRow(r + 1);
                    row.CreateCell(0).SetCellValue(m.ClassificationCode ?? string.Empty);
                    row.CreateCell(1).SetCellValue(m.ClassificationName ?? string.Empty);
                    row.CreateCell(2).SetCellValue(m.Sort);
                    row.CreateCell(3).SetCellValue(m.Status == 1 ? "启用" : "禁用");
                    row.CreateCell(4).SetCellValue(m.Remark ?? string.Empty);
                    row.CreateCell(5).SetCellValue(m.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    row.CreateCell(6).SetCellValue(m.CreateUser ?? string.Empty);
                }

                using var ms = new MemoryStream();
                wb.Write(ms);
                ms.Flush();
                var bytes = ms.ToArray();

                return new APIResult<byte[]>
                {
                    Code = APIEnums.Success,
                    Msg = $"成功导出{data.Count}条数据",
                    Data = bytes
                };
            }
            catch (Exception ex)
            {
                return new APIResult<byte[]>
                {
                    Code = APIEnums.Fail,
                    Msg = "导出失败：" + ex.Message,
                    Data = Array.Empty<byte>()
                };
            }
        }
    }
}
